package eliauk.fun.flowabledemo.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class TaskAutoCompleter {

    @Autowired
    private TaskService taskService;

    @Scheduled(fixedRate = 60000) // 每1分钟检查一次  
    public void checkDueTasks() {
        List<Task> tasks = taskService.createTaskQuery()
                .taskDueBefore(new Date()) // 查询已过期的任务  
                .list();
        for (Task task : tasks) {
            if (task.getName().equals("协理审核")) {
                // 添加审核批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), "taskResult", "true");
                taskService.addComment(task.getId(), task.getProcessInstanceId(), "taskComment", "审核通过");
                taskService.addComment(task.getId(), task.getProcessInstanceId(), "taskResultMessage", "自动通过");
                // 添加流程变量
                DateTime dateTime = DateUtil.offsetMinute(new DateTime(), 30);
                HashMap<String, Object> variables = new HashMap<>();
                variables.put("assignee", "局长");
                variables.put("dueDate",dateTime);
                // 完成任务
                taskService.complete(task.getId(),variables); // 自动完成任务
            }
        }
    }
}